// Tweets fetching Query
var szURLTweet1 = "https://query.yahooapis.com/v1/public/yql?q=select%20status.text%2Cstatus.created_at%2Cstatus.user.screen_name%20from%20twitter.user.timeline%20where%20screen_name%3D'";
var szURLTweet2 = "'&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";

// number of tweets to show
// TODO: can be added into a configuration.
var nTweetShowCount = 10;

// Friends fetching Query
var szURLFrn1 = "https://query.yahooapis.com/v1/public/yql?q=select%20screen_name%20from%20twitter.users%20where%20id%20in%20(select%20id%20from%20twitter.friends%20where%20id%3D'";
var szURLFrn2 = "')&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=";

// current tweet count
var nTweetCount = 0;
/** ************************************************************************* */
// function to fetch URL DATA
// input: URL = to fetch data from
// input: callback = function that handles data
// input: div id to put data
function readURL_ajax(szURL, callBack, divid) {
	try {
		// create an AJAX request
		var ajaxReq = new XMLHttpRequest();
		// setup a status change
		ajaxReq.onreadystatechange = function() {
			if (ajaxReq.readyState == 4) { // 4 == complete
				// 200 == status OK
				if (ajaxReq.status == 200
						|| window.location.href.indexOf("http") == -1) {
					// if call back function is defined, call it
					if (callBack != null) {
						// convert it to JSON
						var oJSON = gadgets.json.parse(ajaxReq.responseText);
						// give a callback with JSON
						callBack(oJSON, divid);
					}
					// else dont know what to do.
				} else {
					errors += "AJAX: URL : " + szURL + "Status: "
							+ ajaxReq.status + "<br/>";
				}
			}
		};
		// request to GET the url, callback will be called
		ajaxReq.open("GET", szURL, true);
		ajaxReq.send(null);
	} catch (ex) {
		handleException("readURL_ajax()" + ex.description);
	}
}

// same method, but using gadgets.io.makerequest
// input: URL = to fetch data from
// input: callback = function that handles data
// input: div id to put data
// @Deprecated: this method gives stale data, hence not using
function readURL(szURL, callBack, divid) {
	try {
		var params = {};
		params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;

		gadgets.io.makeRequest(szURL, function(response) {
			callBack(response, divid);
		}, params);

	} catch (ex) {
		handleException("readURL()" + ex.description);
	}
}

// given user name, create a url & fetch friends JSON
function getFriendsJSON(szUser, divid) {
	showMessage(szUser);
	// 1. generate URL based on user name
	var URL = szURLFrn1 + szUser + szURLFrn2;
	// 2. read URL output
	readURL(URL, getFriendsFromJSON, divid);
}

// callback function to get friends screen ids and get their feeds.
// input: oJSON, json object containing friends screen ids 
// input: div id where tweets to be put
function getFriendsFromJSON(oJSON, divid) {
	try {
		showMessage("in getFriendsFromJSON()");

		if (oJSON != null) {
			for ( var i = 0; i < oJSON.query.count; i++) {
				showMessage(oJSON.query.results.user[i].screen_name);
				getTweetJSON(oJSON.query.results.user[i].screen_name, divid);
			}
		}
	} catch (ex) {
		handleException("getFriendsFromJSON() : " + ex.description);
	}
}

// function to get friends tweets.
// input: szUser, name of the user (screen id)
// input: div id where tweets to be inputs
function getTweetJSON(szUser, divid) {
	// 1. generate URL based on user name
	var URL = szURLTweet1 + szUser + szURLTweet2;
	showMessage("user tweets will be fetched from : "+URL);
	// 2. read URL output & consolidate url output into a single var (JSON object) 
	//readURL(URL, getTweetFromJSON, divid); // this uses gadgets.io.makeRequest(), 
	// it gives stale results for aggregations.
	readURL_ajax(URL, getTweetFromJSON, divid);
}

// callback function to get tweets and show it in given div id.
// input: oJSON, json object containing user tweets
// input: div id where tweets to be put
function getTweetFromJSON(oJSON, divid) {
	try {
		showMessage("in Tweet CallBack()");
		showMessage(oJSON.query.count);
		if (oJSON != null) {
			showMessage(oJSON.query.count);
			var szEntry = "";
			for ( var i = 0; i < oJSON.query.count && i < nTweetShowCount; i++) {
				try {
					szEntry = "<b>"
							+ oJSON.query.results.statuses[i].status.user.screen_name
							+ "</b> : ";
					szEntry += oJSON.query.results.statuses[i].status.text
							+ "<br/>";
					szEntry += "<i>"
							+ oJSON.query.results.statuses[i].status.created_at
							+ "</i> <br/>";
					showMessage("Tweet to be added"+ szEntry);
					document.getElementById(divid).innerHTML += szEntry;
					nTweetCount++;
					// 50 chars per line
					var nlines = szEntry / 50; 
					// added for dynamic size change, 20 pts of height per line
					gadgets.window.adjustHeight(nTweetCount*20*nlines);
				} catch (ex) {
					// not handled
				}
			}
		}
	} catch (ex) {
		handleException("getTweetFromJSON() : " + ex.description);
	}
}
// main function to be called.
// param screen_name of the user
// param divid, div id for the division to be updated with tweets
function getTweetStream(szUser, divid) {
	try{
	// adjust height
	gadgets.window.adjustHeight();
	nTweetCount = 0;
	// clean up previous tweets
	document.getElementById(divid).innerHTML = "";
	// 1. get User's twits
	getTweetJSON(szUser, divid);

	// 2. get User's friends
	// TODO: re enable this to fetch friend tweets
	//getFriendsJSON(szUser, divid);
	} catch (ex) {
		alert("getTweetStream() " + ex.description);
	}
}
